package com.sdonkey.score.util;

/**
 * Created by Administrator on 2019\1\18 0018.
 */
/**
 *@Description:
 */

import java.util.ArrayList;
import java.util.List;


public class RedPackage {
    //最小红包额度
    private Float MINMONEY = 0.01f;
    //最大红包额度
    private Float MAXMONEY = 10f;

    private static final float TIMES = 5.1f;

    public RedPackage(Float MINMONEY, Float MAXMONEY) {
        this.MINMONEY = MINMONEY;
        this.MAXMONEY = MAXMONEY;
    }

    public List<Float> splitRedPackets(float money, int count)
    {
        if(!isRight(money,count))
        {
            return null;
        }
        List<Float> list = new ArrayList<Float>();
        float max = (float)(money*TIMES/count);

        max = max>MAXMONEY?MAXMONEY:max;
        for(int i=0;i<count;i++)
        {
            float one = randomRedPacket(money,MINMONEY,max,count-i);
            list.add(one);
            money-=one;
        }
        return list;
    }
    private float randomRedPacket(float money,float mins,float maxs,int count)
    {
        if(count==1)
        {
            return (float)(Math.round(money*100))/100;
        }
        if(mins == maxs)
        {
            return mins;//如果最大值和最小值一样，就返回mins
        }
        float max = maxs>money?money:maxs;
        float one = ((float)Math.random()*(max-mins)+mins);
        one = (float)(Math.round(one*100))/100;
        float moneyOther = money - one;
        if(isRight(moneyOther,count-1))
        {
            return one;
        }
        else{
            //重新分配
            float avg = moneyOther / (count-1);
            if(avg<MINMONEY)
            {
                return randomRedPacket(money,mins,one,count);
            }else if(avg>MAXMONEY)
            {
                return randomRedPacket(money,one,maxs,count);
            }
        }
        return one;
    }

    /**
     * @param money
     * @param count
     * @return
     * @Author:lulei
     * @Description: 此种红包是否合法
     */
    private boolean isRight(Float money, int count) {
        double avg = money / count;
        if (avg < MINMONEY) {
            return false;
        }
        if (avg > MAXMONEY) {
            return false;
        }
        return true;
    }

    public static void main(String[] args) {
//        // TODO Auto-generated method stub
//        RedPackage util = new RedPackage();
//        System.out.println(util.splitRedPackets(20000f, 10000));
    }
}

